// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Data;
using ValidationAspects;

namespace WpfInterceptionValidation
{
	public class ValidatesOnExceptionsBinding : Binding
	{
		private static readonly UpdateSourceExceptionFilterCallback exceptionFilterCallback = (o, e) =>
		                                                                                      {
		                                                                                      	Exception exception = e;
		                                                                                      	string errorContent = null;

		                                                                                      	if (e is TargetInvocationException && e.InnerException != null)
		                                                                                      		exception = e.InnerException;

		                                                                                      	ValidationException validationException = exception as ValidationException;
		                                                                                      	if (validationException != null)
		                                                                                      	{
		                                                                                      		exception = validationException;
		                                                                                      		errorContent = validationException.Messages.OrderBy(s => s).Aggregate((a, m) => a + Environment.NewLine + m);
		                                                                                      	}

		                                                                                      	return new ValidationError(new ExceptionValidationRule(), o, errorContent ?? exception.Message, exception);
		                                                                                      };

		public ValidatesOnExceptionsBinding(string path) : base(path)
		{
			ValidatesOnExceptions = true;
			UpdateSourceExceptionFilter = exceptionFilterCallback;
		}
	}
}